package com.ebb;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ebb.EBBListActivity.Pagenation;
import com.stackmob.android.sdk.common.StackMobCommon;
import com.stackmob.sdk.api.StackMob;
import com.stackmob.sdk.api.StackMobQuery;
import com.stackmob.sdk.callback.StackMobCallback;
import com.stackmob.sdk.exception.StackMobException;

public class EBBViewActivity extends Activity implements OnClickListener {
	private static final String TAG = EBBViewActivity.class.getCanonicalName();
	private StackMob stackmob;
	private Intent intent;
	private TextView viewText;
	private TextView viewNickName;
	private TextView viewDate;
	private Button btnLogout;
	private EditText etComment;
	private Button btnComment;
	private String bbsId; // �Խù� id
    private String bbsOwnerUsername; // �Խù� �ۼ���
	private LinearLayout commentList;	
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view);

		EBBAlert.setContext(EBBViewActivity.this);
		EBBAlert.setDuration(Toast.LENGTH_SHORT);

		stackmob = StackMobCommon.getStackMobInstance();
		
		EBBC2DMRegistrationIDHolder regHolder = new EBBC2DMRegistrationIDHolder(this);
		if (regHolder.hasID()) {
			try {
				Log.i(TAG, "registration ID " + regHolder.getID() + " was already stored in shared prefs");
				EBBAlert.message(1, null, "registration ID " + regHolder.getID() + " was already stored in shared prefs");
			}
			catch (EBBC2DMRegistrationIDHolder.NoStoredRegistrationIDException e) {
				Log.e(TAG, "failed to get registration ID from shared prefs, even though shared prefs reports that it's there" , e);
				EBBAlert.message(1, null, "failed to get registration ID from shared prefs, even though shared prefs reports that it's there");
			}
		} else {
			Log.i(TAG, "registration ID was not already stored in shared prefs. fetching a new one and saving it");
			EBBAlert.message(1, null, "registration ID was not already stored in shared prefs. fetching a new one and saving it");
			try {
				requestRegistrationId();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		initLayout();
		setBBSView();
		loadCommentList();
		resetUnreadCount();
	}
	
	public void requestRegistrationId() throws Exception {
		try {
			EBBAlert.message(1, null, getRegistrationIDHolder().getID());
		}
		catch(EBBC2DMRegistrationIDHolder.NoStoredRegistrationIDException e) {
			Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
			intent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
			intent.putExtra("sender", "apexcns.test@gmail.com");
			startService(intent);
		}
	}
	
	private EBBC2DMRegistrationIDHolder getRegistrationIDHolder() {
		return new EBBC2DMRegistrationIDHolder(EBBViewActivity.this);
	}

	// �Խ��� view ����
	private void setBBSView() {
		Bundle bundle = getIntent().getExtras();
		this.bbsId = bundle.getString("bbsId");
		this.bbsOwnerUsername = bundle.getString("bbsOwnerUsername");

		this.viewText = (TextView) findViewById(R.id.view_text);
		this.viewNickName = (TextView) findViewById(R.id.view_nick_name);
		this.viewDate = (TextView) findViewById(R.id.view_date);

		stackmob.get("bbs/" + bbsId, new StackMobCallback() {
			@Override
			public void success(String responseBody) {
				Log.d(TAG, "## get object >  #" + responseBody);

				final JSONObject jsonObject;
				try {
					jsonObject = new JSONObject(responseBody);
					final String content = jsonObject.getString("content");
					final String nickname = jsonObject.getString("nickname");
					final String createddate = jsonObject.getString("createddate");

					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							viewText.setText(content);
							viewNickName.setText(nickname);

							// ����
							SimpleDateFormat sd = new SimpleDateFormat(
									"dd/MM/yy, HH:mm");
							long date = Long.parseLong(createddate);
							viewDate.setText(sd.format(date));
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void failure(StackMobException e) {
				e.printStackTrace();
			}
		});
	}

	// ��� list �ε�!
	private void loadCommentList() {
		this.commentList.removeAllViewsInLayout();
		
		// �ش� bbsid �� unread_count�� 0����
		

		StackMobQuery q = new StackMobQuery("comment").fieldIsOrderedBy(
				"createddate", StackMobQuery.Ordering.DESCENDING)
				.fieldIsEqualTo("bbs_id", bbsId);

		stackmob.get(q, new StackMobCallback() {
			@Override
			public void success(final String responseBody) {
				Log.d(TAG, " loadCommentList success ");

				try {
					final JSONArray jsonArray = new JSONArray(responseBody);
					int count = jsonArray.length();
					Pagenation.setNowPageTotalCount(count);

					if (count > 0) {
						// comment row �߰�
						for (int i = 0; i < jsonArray.length(); i++) {
							final JSONObject commentObject = jsonArray
									.getJSONObject(i);

							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									try {
										String content = commentObject
												.getString("content");

										// content of comment
										LinearLayout ll = new LinearLayout(
												getApplicationContext());
										ll.setGravity(android.view.Gravity.RIGHT);
										ll.setOrientation(LinearLayout.VERTICAL);
										ll.setPadding(10, 10, 10, 10);

										TextView tv = new TextView(
												getApplicationContext());
										tv.setWidth(550);
										tv.setHeight(60);
										tv.setPadding(10, 10, 10, 10);
										tv.setBackgroundColor(Color
												.parseColor("#FFFFFF"));
										tv.setTextColor(Color
												.parseColor("#000000"));
										tv.setText(content);

										ll.addView(tv);
										commentList.addView(ll);

										// nickname & date of comment
										LinearLayout subll = new LinearLayout(
												getApplicationContext());
										subll.setGravity(android.view.Gravity.RIGHT);
										subll.setPadding(10, 10, 10, 10);

										String nickname = commentObject
												.getString("nickname");
										SimpleDateFormat sd = new SimpleDateFormat(
												"dd/MM/yy, HH:mm");
										long date = Long.parseLong(commentObject
												.getString("createddate"));
										String createddate = sd.format(date);

										tv = new TextView(
												getApplicationContext());
										tv.setPadding(10, 10, 10, 10);
										tv.setText(nickname.concat("  ")
												.concat(createddate));

										subll.addView(tv);

										ll.addView(subll);

									} catch (JSONException e) {
										e.printStackTrace();
									}
								}
							});
						}
					}
				} catch (Exception e) {
					Log.d(TAG, " json parsing error : " + e.getMessage());
					e.printStackTrace();
				}
			}

			@Override
			public void failure(StackMobException e) {
				Log.d(TAG, " error : " + e.getMessage());
				e.printStackTrace();
			}
		});
	}

	// bbs id�� ���� user�� �̸��� checknew���� ã�� ���� checknew_id������ resetCount ȣ��
	private void resetUnreadCount() {		
		StackMobQuery q = new StackMobQuery("checknew").fieldIsEqualTo("bbs_id", bbsId);

		stackmob.get(q, new StackMobCallback() {
			@Override
			public void success(final String responseBody) {
				Log.d(TAG, " reset start ");

				try {
					final JSONArray jsonArray = new JSONArray(responseBody);
					int count = jsonArray.length();					

					if (count > 0) {
						// comment row �߰�
						for (int i = 0; i < jsonArray.length(); i++) {
							final JSONObject checknewObject = jsonArray.getJSONObject(i);
							if(checknewObject.getString("username").equals(EBBUser.getInstance().getUserName())) {
								Log.d(TAG, " try reset ");
								resetCount(checknewObject.getString("checknew_id"));
							}
						}
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			
			@Override
			public void failure(StackMobException e) {
				Log.d(TAG, " error : " + e.getMessage());
				e.printStackTrace();
			}
		});
		
	}
	
	// ��޹��� checknew_id�� �ش� unread_count 0���� ����
	protected void resetCount(String checknewId) {
		Map<String, Integer> args = new HashMap<String, Integer>();		
		args.put("unread_count", 0);	
		
		stackmob.put("checknew", checknewId, args, new StackMobCallback(){
			@Override
			public void success(String responseBody) {
				Log.d(TAG, "unread_count set 0");
			}
			
			@Override
			public void failure(StackMobException e) {
				Log.d(TAG, " error : " + e.getMessage());
				e.printStackTrace();
			}
		});
					
	}

	private void initLayout() {
		this.etComment = (EditText) findViewById(R.id.comment_text);
		this.commentList = (LinearLayout) findViewById(R.id.comment_list);

		this.btnLogout = (Button) findViewById(R.id.logout_button);
		this.btnComment = (Button) findViewById(R.id.comment_button);

		this.btnLogout.setId(0x4001);
		this.btnComment.setId(0x4002);

		this.btnLogout.setOnClickListener(this);
		this.btnComment.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case 0x4001: // Logout
			stackmob.logout(new StackMobCallback() {
				@Override
				public void success(String response) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							EBBAlert.message(1, null, "Logout Success!");
							setIntent("com.ebb.EBBStackMobLoginActivity");
							EBBUser.getInstance().logout();
						}
					});
				}

				@Override
				public void failure(StackMobException e) {
					e.printStackTrace();
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							EBBAlert.message(1, null, "Logout Failure!");
						}
					});
				}
			});
			break;
		case 0x4002: // save acomment
			String content = etComment.getText().toString();
			HashMap<String, Object> fields = new HashMap<String, Object>();

			fields.put("sm_owner", EBBUser.getInstance().getUserName());
			fields.put("nickname", EBBUser.getInstance().getNickName());
			fields.put("content", content);
			fields.put("bbs_id", bbsId);

			stackmob.post("comment", fields, new StackMobCallback() {
				@Override
				public void success(String responseBody) {
					Log.d(TAG, "successed! >>>>>>" + responseBody);
					loadCommentList();
					
					updateUnreadCount();
				}
                @Override
				public void failure(StackMobException e) {
					Log.d(TAG, "error.." + e.getMessage());
					e.printStackTrace();
				}
			});
			// push to Owner
			final Map<String, String> payload = new HashMap<String, String>();
			payload.put("payload", "New BonBon");
			EBBAlert.message(1, null, "payload: " + payload.get("payload"));
//			StackMobPushToken token = new StackMobPushToken(getRegistrationIDHolder().getID(), StackMobPushToken.TokenType.Android);
//			StackMobCommon.getStackMobInstance().pushToTokens(payload, Arrays.asList(token), new StackMobCallback() {
			StackMobCommon.getStackMobInstance().broadcastPushNotification(payload, new StackMobCallback() {
//			stackmob.pushToUsers(payload, Arrays.asList("test"), new StackMobCallback() {
				@Override
				public void success(String s) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							EBBAlert.message(1, null, "Send Success!");
						}
					});
				}
				
				@Override
				public void failure(StackMobException e) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							EBBAlert.message(1, null, "Send Failure!");
						}
					});
					e.printStackTrace();
				}
			});

			etComment.setText("");
			break;
		}

	}
	
    private void updateUnreadCount() {
        // 0. bbs owner�� ����ϴ� ����̶�� skip
        if(bbsOwnerUsername.equals(EBBUser.getInstance().getUserName())) return;
        
        // 1. bbsId�� �ش��ϴ� checknew ������ �����ͼ�
        StackMobQuery query = new StackMobQuery("checknew").fieldIsEqualTo("bbs_id", bbsId);
        stackmob.get(query, new StackMobCallback() {
            @Override 
            public void success(String responseBody) {
                JSONArray jsonArray;
                try {
                    jsonArray = new JSONArray(responseBody);

                    int count = jsonArray.length();

                    if(count > 0) {
                        JSONObject jsonObject = jsonArray.getJSONObject(0);
                        String idValue = jsonObject.getString("checknew_id");
                        
                        //2. �ش� chekenw�� unread_count ���� ��=1=1=1=1-��   
                        stackmob.updateAtomicCounter("checknew", idValue, "unread_count", 1, new StackMobCallback() {
                            @Override 
                            public void success(String responseBody) {
                                // 3. push ���
                                
                            }
                            @Override 
                            public void failure(StackMobException e) {
                                e.printStackTrace();
                            }
                        }); 
                    }
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
            }
            @Override 
            public void failure(StackMobException e) {
                e.printStackTrace();
            }
        });
                 
    }	

	private void setIntent(String activity) {
		intent = new Intent(activity);
		startActivity(intent);
	}
}
